﻿using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using JasLib.Extensions;
using JasLib.Wpf;

namespace WpfFizzBuzz.ViewModels
{
    public class MultipleViewModel : ViewModelBase<MultipleViewModel>
    {
        private FactorViewModel[] _factorViewModels = null;

        private int _iMultiple = 1;
        public int Multiple
        {
            get { return _iMultiple; }
        }

        #region Name property.

        /// <summary>
        /// Unfortunately, read-only dependency properties cannot have source bindings.
        /// I don't see the point of that restriction.
        /// </summary>
        public readonly static DependencyProperty NameProperty = DependencyProperty.Register(
            "Name",
            typeof(string),
            typeof(MultipleViewModel),
            new FrameworkPropertyMetadata(
                null,
                FrameworkPropertyMetadataOptions.None,
                new PropertyChangedCallback(NameProperty_Changed),
                new CoerceValueCallback(NameProperty_Coerce)));

        private static void NameProperty_Changed(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
        }

        private static object NameProperty_Coerce(DependencyObject d, object newValue)
        {
            return (d as MultipleViewModel)._factorViewModels.Select(vm => vm.Name).Join();
        }

        public string Name
        {
            get { return (string)GetValue(NameProperty); }
            //set { SetValue(NameProperty, value); }
        }

        #endregion

        public MultipleViewModel(int iMultiple, IEnumerable<FactorViewModel> factorViewModels)
        {
            _factorViewModels = factorViewModels.AsArray();
            _iMultiple = iMultiple;

            MultiBinding binding = new MultiBinding();
            binding.Converter = new JoinStringsMultiValueConverterExtension();
            foreach (var viewModel in factorViewModels)
                binding.AddPropertyPathBinding(viewModel, vm => vm.Name);
            this.SetBinding(NameProperty, binding);
            return;
        }
    }

}
